import { ReactiveEffect } from './effect';
class ComputedRefImpl {
    private _getter: any;
    
    // _dirty用作缓存用
    private _dirty: boolean = true;
    private _value: any;
    private _effect: ReactiveEffect;
    constructor(getter) {
        this._getter = getter;
        // 通过调度器，当getter值发生变化时，dirty置为true
        this._effect = new ReactiveEffect(getter, () => {
            if (!this._dirty) {
                this._dirty = true;
            }
        });
    }

    get value() {
        // 调用一次后直接锁上
        if (this._dirty) {
            this._dirty = false;
            // 将第一次调用的值存储起来
            this._value = this._effect.run();
        }
        // 第二次获取的值直接返回第一次的值
        return this._value;
    }
}

export function computed(getter) {
    return new ComputedRefImpl(getter);
}